// web/src/app/api/(learn)/course/[courseId]/chapters/[chapterId]/unpublish/route.ts

import {NextRequest, NextResponse} from "next/server";
import {currentUser} from "@/lib/auth";
import {db} from "@/lib/db";

export async function PATCH(
    req: NextRequest,
    {params}: { params: { courseId: string; chapterId: string } }
) {
    try {
        const user = await currentUser()
        if (!user) return new NextResponse('Unauthorized', {status: 401})

        const courseOwner = await db.course.findUnique({
            where: {
                id: params.courseId,
                userId: user.id
            }
        })

        if (!courseOwner) {
            return new NextResponse('Unauthorized', {status: 401})
        }

        const unpublishedChapters = await db.chapter.update({
            where: {
                courseId: params.courseId,
                id: params.chapterId,
            },
            data: {
                isPublished: false
            }
        })

        // 当前没有发布过的chapter
        const publishedChaptersInCourse = await db.chapter.findMany({
            where: {
                courseId: params.courseId,
                isPublished: true
            }
        })

        // 则课程设置为非公开
        if (!publishedChaptersInCourse.length) {
            await db.course.update({
                where: {
                    id: params.courseId
                },
                data: {
                    isPublished: false
                }
            })
        }

        return NextResponse.json(unpublishedChapters)
    } catch (e) {
        console.error('[CHAPTER_UNPUBLISH]', e)
        return new NextResponse('Internal Server Error', {status: 500})
    }
}